package com.arvin.imagepicker.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.arvin.imagepicker.AndroidImagePicker;
import com.arvin.imagepicker.R;
import com.arvin.imagepicker.bean.ImageItem;
import com.arvin.imagepicker.ui.ImagePreviewFragment;
import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jp on 2018/7/17.
 */

public class ImagePickView extends ViewGroup implements CustomImgDialog.OnDeleteListener,AndroidImagePicker.OnImagePickCompleteListener {
    private Context mContext;
    private List<ImageItem> mPics=new ArrayList<>();
    private final RecyclerView mRecyclerView;
    private final int  COUNT=4;
    private final int mItemHeight;
    private boolean mCanEdit;
    private MineAdapter mAdapter;
    private CustomImgDialog.OnMultiDeleteListener mOnMultiDeleteListener;
    private final String mFileType;
    private String mRowIndex;

    public String getmRowIndex() {
        return mRowIndex;
    }

    public void setmRowIndex(String mRowIndex) {
        this.mRowIndex = mRowIndex;
    }

    public List<ImageItem> getPics()
    {
        return mPics;
    }

    public void setPics(List<ImageItem> list) {
        if(list!=null&&list.size()>0)
        {
            mPics.clear();
            mPics.addAll(list);
            mAdapter.notifyDataSetChanged();
        }

    }
    public void addPic(ImageItem imageItem)
    {
        mPics.add(imageItem);
        mAdapter.notifyDataSetChanged();
    }




    public void setOnMultiDeleteListener(CustomImgDialog.OnMultiDeleteListener listener)
    {
        mOnMultiDeleteListener=listener;
    }

    public ImagePickView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.params);
        mCanEdit = typedArray.getBoolean(R.styleable.params_canEdit, true);
        mFileType = typedArray.getString(R.styleable.params_fileType);
        typedArray.recycle();
        DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
        mItemHeight = displayMetrics.widthPixels / COUNT;
        mRecyclerView = new RecyclerView(context);
        initRecycler();
        this.addView(mRecyclerView);
    }

    private void initRecycler() {
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        mRecyclerView.setLayoutParams(layoutParams);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, COUNT);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mAdapter=new MineAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setNestedScrollingEnabled(false);
    }


    /**
     * 是否可编辑
     * @param canEdit
     */
    public void setCanEdit(boolean canEdit){
        mCanEdit=canEdit;
        invalidate();
        requestLayout();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChild(mRecyclerView,widthMeasureSpec,heightMeasureSpec);
        setMeasuredDimension(mRecyclerView.getMeasuredWidth(),mRecyclerView.getMeasuredHeight());
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        mRecyclerView.layout(paddingLeft,paddingTop,width-paddingRight,height-paddingBottom);

    }

    @Override
    public void onDelete() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onImagePickComplete(List<ImageItem> items) {
        if(items!=null)
        {
            for(int i=0;i<items.size();i++)
            {
                ImageItem item = items.get(i);
                item.type=mFileType;
                File file = new File(item.path);
                if(!file.exists()||file.length()==0)
                {
                    items.remove(i);
                    --i;
                }
            }

            mPics.addAll(items);
            mAdapter.notifyDataSetChanged();
        }
    }


    class MineAdapter extends RecyclerView.Adapter
    {
        final int normal=0;
        final int footer=1;
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            switch (viewType)
            {
                case normal:
                    View normal = LayoutInflater.from(mContext).inflate(R.layout.item_pic, parent, false);
                    LayoutParams layoutParams = normal.getLayoutParams();
                    layoutParams.height=mItemHeight;
                    normal.setLayoutParams(layoutParams);
                    return new Holder(normal);

                case footer:
                    View footer = LayoutInflater.from(mContext).inflate(R.layout.item_add, parent, false);
                    LayoutParams layoutParams1 = footer.getLayoutParams();
                    layoutParams1.height=mItemHeight;
                    footer.setLayoutParams(layoutParams1);
                    return new AddHolder(footer);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            if(holder instanceof Holder)
            {

                ImageItem item = mPics.get(position);
                if(!TextUtils.isEmpty(item.path))
                {
                    Glide.with(mContext).load(new File(item.path)).into(((Holder)holder).iv);
                }else if(!TextUtils.isEmpty(item.url))
                {
                    Glide.with(mContext).load(item.url).into(((Holder)holder).iv);
                }

                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CustomImgDialog customImgDialog = new CustomImgDialog(mContext, R.style.CustomDialog_fill, mPics, mCanEdit, position);
                        customImgDialog.setOnDeleteListener(ImagePickView.this);
                        customImgDialog.setOnMultiDeleteListener(mOnMultiDeleteListener);
                        customImgDialog.show();

                    }
                });
            }else if(holder instanceof AddHolder)
            {
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AndroidImagePicker.getInstance().pickMulti(mContext, true,ImagePickView.this);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            if(mCanEdit)
            {
                return mPics.size()+1;
            }else {
                return mPics.size();
            }
        }

        @Override
        public int getItemViewType(int position) {
            if(mCanEdit)
            {
                if(position==getItemCount()-1)
                {
                    return footer;
                }else {
                    return normal;
                }
            }else {
                return normal;
            }
        }



    }
    
    
    class Holder extends RecyclerView.ViewHolder
    {
        ImageView iv;
        public Holder(View itemView) {
            super(itemView);
            
            initView(itemView);
        }

        private void initView(View itemView) {
            iv= (ImageView)itemView.findViewById(R.id.iv);
        }

    }


    class AddHolder extends RecyclerView.ViewHolder
    {

        public AddHolder(View itemView) {
            super(itemView);
        }
    }
}
